package com.quanyan.user.service.admin.impl;

import com.alibaba.fastjson.JSON;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.Limit;
import com.quanyan.messagepush.entity.Alert;
import com.quanyan.messagepush.entity.Payload;
import com.quanyan.messagepush.entity.PushMessage;
import com.quanyan.messagepush.entity.ReqPushMessage;
import com.quanyan.messagepush.enums.BoxName;
import com.quanyan.messagepush.enums.BoxType;
import com.quanyan.messagepush.enums.MsgType;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.TbUserVerifyMapper;
import com.quanyan.user.mapper.UserExtMapper;
import com.quanyan.user.mapper.UserVerifyMapper;
import com.quanyan.user.model.db.TbUser;
import com.quanyan.user.model.db.TbUserExt;
import com.quanyan.user.model.db.TbUserVerify;
import com.quanyan.user.model.db.TbUserVerifyExample;
import com.quanyan.user.model.vo.request.ReqUserAuditParam;
import com.quanyan.user.model.vo.request.admin.ReqUserVerifyQuery;
import com.quanyan.user.service.UserExtService;
import com.quanyan.user.service.UserInformationService;
import com.quanyan.user.service.admin.UserVerifyService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by hua on 2016/8/4.
 */
@Service
public class UserVerifyServiceImpl implements UserVerifyService {
    private static final Logger logger = LoggerFactory.getLogger(UserVerifyServiceImpl.class);
    @Autowired
    private UserVerifyMapper userVerifyMapper;
    @Autowired
    private UserExtMapper userExtMapper;
    @Autowired
    private TbUserVerifyMapper tbUserVerifyMapper;
    @Autowired
    private UserExtService userExtService;
    @Autowired
    private UserInformationService userInformationService;
    @Value("${message.push.service.url}")
    public String messagePushServiceUrl;
    private static String LARK_LOGO = "lark_icon.png";

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public PageObj<List<TbUserVerify>> queryUserVerifyList(ReqUserVerifyQuery userVerifyQuery) {
        List<TbUserVerify> result = new ArrayList<>();
        TbUserVerifyExample example = new TbUserVerifyExample();
        TbUserVerifyExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(userVerifyQuery.getIdCard())) {
            criteria.andIdCardLike("%" + userVerifyQuery.getIdCard() + "%");
        }
        if (StringUtils.isNotBlank(userVerifyQuery.getName())) {
            criteria.andNameLike("%" + userVerifyQuery.getName() + "%");
        }
        if (null != userVerifyQuery.getStatus()) {
            criteria.andStatusEqualTo(userVerifyQuery.getStatus());
        }
        if (null != userVerifyQuery.getStartTime()) {
            criteria.andCreateTimeBetween(DateUtils.dayBegin(userVerifyQuery.getStartTime()), DateUtils.dayEnd(userVerifyQuery.getEndTime()));
        }

        int total = tbUserVerifyMapper.countByExample(example);
        if (total > 0) {
            example.setLimit(Limit.buildLimit(userVerifyQuery.getPageNo(),userVerifyQuery.getPageSize()));
            example.setOrderByClause("create_time desc");
            result = tbUserVerifyMapper.selectByExample(example);
        }

        return PageObj.create(total, userVerifyQuery.getPageNo(), userVerifyQuery.getPageSize(), result);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void verifyUser(ReqUserAuditParam userAuditParam) {
        try {
            //更新更新实名认证表
            userVerifyMapper.updateUserVerify(userAuditParam);
            TbUserVerify userVerify = tbUserVerifyMapper.selectByPrimaryKey(userAuditParam.getId());
            if (userVerify != null) {
                //更新用户信息拓展表实名认证状态
                userExtMapper.updateNameVerifyStatus(userVerify.getUid(), userAuditParam.getStatus());

                TbUserExt userExt = new TbUserExt();
                userExt.setUid(userVerify.getUid());
                userExt.setNameVerifyStatus(userAuditParam.getStatus());
                userExtService.updateUserExt(userExt);

                if (userAuditParam.getStatus().intValue() == 2) {  //审核通过，更新user表真实姓名
                    TbUser tbUser = new TbUser();
                    tbUser.setId(userVerify.getUid());
                    tbUser.setName(userAuditParam.getRealName());
                    userInformationService.updateUser(tbUser,userVerify.getUid());
                }

                //消息推送
                String msg;
                if (userAuditParam.getStatus().intValue() == 2)
                    msg = "您的实名认证资料已成功通过审核。";
                else
                    msg ="您的实名认证资料未通过审核,原因为：" + userAuditParam.getRemark() +"请重新提交认证。";

                ReqPushMessage reqPushMessage = new ReqPushMessage();
                PushMessage pushMessage = new PushMessage();
                pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
                Alert alert = new Alert();
                alert.setBody("系统通知：" + msg);
                pushMessage.setAlert(alert);

                pushMessage.setTo(Arrays.asList(userVerify.getUid()));
                pushMessage.setLogo(LARK_LOGO);
                pushMessage.setLogoUrl("");
                Payload payload = new Payload();
                payload.setBoxType(BoxType.SYSTEM_MSG.value());
                payload.setMsgType(MsgType.NOTIFY_MSG.value());
                payload.setTitle(msg);
                payload.setImg(UserConstants.SYSTEM_MESSAGE_URL);
                payload.setTimestamp(System.currentTimeMillis());

                pushMessage.setPayload(payload);
                reqPushMessage.setMsgList(Arrays.asList(pushMessage));

                this.pushMsg(reqPushMessage);
            }
        } catch (Exception e) {
            logger.error("用户实名认证出错", e.getMessage());
        }

    }

    private void pushMsg(ReqPushMessage reqPushMessage) {
        try {
            String postJson = JSON.toJSONString(reqPushMessage);
            logger.info("推送消息：" + postJson);
            String result = HttpClientUtils.postJson(messagePushServiceUrl, postJson);
            logger.info("推送返回：" + result);
        } catch (Exception e) {
            logger.error("推送消息失败，" + e.getMessage());
        }
    }
}
